<?php
namespace App\Models\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class Order extends Common {
    protected $table = 'tbuy_order';

    /**
     * 获取所有代购订单信息
     */
    public function get_purchas_order() {
        return DB::table('tbuy_order')->where('order_type',2)->orderBy('order_id', 'desc')->paginate(20);
    }

    /**
     * 模糊查询代购订单信息（根据订单编号）
     * @param `order_no`
     */
    public function get_purchas_order_by_order_no($order_no) {
        if(!$order_no) {
            return false;
        }

        return DB::table('tbuy_order')->where('order_no','like','%'.$order_no.'%')->orderBy('order_id','desc')->paginate(20);
    }

    /**
     * 根据订单ID号，查询订单信息
     * @param `id`  订单ID号
     */
    public function get_order_by_id($id) {
        if(!$id || !is_numeric($id)) {
            return false;
        }

        //查询订单信息
        return DB::table('tbuy_order')->where('order_id',$id)->first();
    }

    /**
     * 根据订单ID号，查询订单详细信息
     * @param `order_id`   订单ID号
     */
    public function get_order_detail($order_id) {
        if(!$order_id) {
            return false;
        }
        //查询订单信息
        return DB::table('tbuy_order_details')->where('order_id',$order_id)->get();
    }

    /**
     * 查询所有代购订单信息
     */
    public function get_purchas_order_detail() {
        return DB::table('tbuy_order_details')->orderBy('details_id','desc')->get();
    }

    /**
     * 根据订单ID号，查询订单的收货地址
     * @param `id`  订单ID号
     */
    public function get_consignee_by_id($id) {
        if(!$id) {
            return false;
        }
        return DB::table('tbuy_order_consignee')->where('order_id',$id)->first();
    }

    /**
     * 根据产品ID号，查询订单详情信息
     * @param `product_id`  产品ID号
     **/
    public function get_order_detail_by_product_id($product_id) {
        if(!$product_id || !is_numeric($product_id)) {
            return false;
        }
        //查询数据
        return DB::table('tbuy_order_details')->select('order_id','amount','buy_count')->where('product_id',$product_id)->get();
    }


    /**
     * 获取订单列表
     */
    public function get_order_list($keyword){
        $where = [
            ['status' , '=' , '1'],
        ];
        if($keyword){
            $where[] = ['order_no' , 'like' , '%'.$keyword.'%'];
        }
        $order = $this
            ->where($where)
            ->orderBy('order_id', 'desc')
            ->paginate(20);

        foreach($order as $k => &$o){
            $user = DB::table('tnet_reginfo t')
                        ->where(['t.nodeid'=>$o['node_id']])
                        ->select('t.nodeid','t.nodename','t.nodecode','t.introducer','t2.nodecode as introducer_nodecode')
                        ->leftJoin('tnet_reginfo t2' , 't.introducer' , '=' , 't2.nodeid')
                        ->first();
            $o->user = $user;

            $details = DB::table('tbuy_order_details')
                                ->where(['order_id'=>$o['order_id']])
                                ->select('details_id','product_id','product_name','amount','buy_count','status')
                                ->get();
            $o->details = $details;

            $product_name = [];
            foreach($details as $d){
                $product_name[] = $d->product_name;
            }
            $o->product_name = implode(',' , $product_name);
        }
        return $order;
    }

   /**
     * 获取线下订单列表
     */
    public function get_lineorder_list($order_no,$pay_state,$sid,$input=[]){
        if(empty($input['sort'])){
            $sort='asc';
        }else{
            $sort=$input['sort'];
        }
        if(empty($input['pagesize'])){
            $pageSize=10;
        }else{
            $pageSize=$input['pagesize'];
        }
        $where = array();
        if($order_no){
            $where[] = ['vshops_order.order_no' , '=' ,$order_no];
        }
        if($pay_state){
            $where[] = ['vshops_order.pay_state' , '=' ,$pay_state];
        }
        $where[] = ['vshops_order.sid' , '=' ,$sid];
        $query = DB::table('vshops_order')
            ->where($where)
            ->where('vshops_order.pay_state',2)
            ->leftJoin('tnet_reginfo t1','t1.nodeid','=','vshops_order.nodeid')
            ->select('vshops_order.*','t1.nodecode')
            ->orderBy('vshops_order.id',$sort);
        if(!empty($input)){
            if (!empty($input['s_time'])){
                $query->where('vshops_order.add_time','>=',$input['s_time']);
            }
            if (!empty($input['e_time'])){
                $query->where('vshops_order.add_time','<=',$input['e_time']);
            }
            if(!empty($input['keyname']) and !empty($input['keyval'])){
                switch ($input['keyname']){
                    case 'order_no':
                        $query->where('vshops_order.order_no',$input['keyval']);
                        break;
                    case 'mobile':
                        $query->where('t1.nodecode',$input['keyval']);
                        break;
                    default;
                }
            }
            if(isset($input['export']) and $input['export']=='true'){
                if($input['details_list']){
                    $query->whereIn('vshops_order.id',explode(',',$input['details_list']));
                }
                return $query->get();
            }
        }
        $order=$query->paginate($pageSize);
        return $order;
    }


    /**
     * 解析订单支付方式
     */
    public function parsePayType($pay_type_json){
        $pay_type = json_decode($pay_type_json , true);

        $result = [];
        $name = '';
        foreach($pay_type as $p){
            switch($p['PayType']){
                case 1 : { // 数据库存储的为分
                    $name = '储值积分';
                    break;
                }
                case 2 : { // 全球积分
                    $name = '全球积分';
                    break;
                }
                case 16 : { // 微信app
                    $name = '微信APP';
                    break;
                }
                case 8 : { // 微信jsapi
                    $name = '微信';
                    break;
                }
                case 32 : { // 支付宝
                    $name = '支付宝';
                    break;
                }
                case 256 : { // 快捷支付
                    $name = '快捷支付';
                    break;
                }
            }
            $result[$p['PayType']] = [
                'amount' => $p['PayAmount'] / 100,
                'name' => $name,
            ];
        }
        return $result;
    }

    /**
     * 手机支付订单转成EXCEL格式
     *
     * @param $query
     * @return array
     */
    public static function parseToExcel($query)
    {
        $data=[];
        foreach ($query as $k=>$v){
            $data[]=[
                $k+1,
                $v->order_no,
                $v->nodecode,
                $v->add_time,
                floatval($v->make_money),
                floatval($v->make_money)*(100-$v->rebate)/100,
                floatval($v->deposit),
                floatval($v->make_money)*0.006,
                floatval($v->real_income)
            ];
        }
        return $data;
    }

    /**
     * 获取手机订单总营业额
     *
     * @param $sid ADMIN UID
     * @return float
     */
    public function getIncome($sid)
    {
        $res = DB::table('vshops_order')->where('sid',$sid)
            ->where('pay_state',2)
            ->sum('make_money');
        return floatval($res);
    }

    /**
     * 手机订单应结算总额之和
     *
     * @param $sid
     * @return float
     */
    public function getRealIncome($sid)
    {
        $res=DB::table('vshops_order')->where('sid',$sid)
            ->where('pay_state',2)
            ->sum('real_income');
        return floatval($res);
    }

    /**
     * 获取订单数
     *
     * @param $sid
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function getOrderNumByTimeRange($sid,$startDate, $endDate)
    {
        $where = [$startDate, $endDate];
        $regTrendList = DB::table('vshops_order')
            ->where('sid',$sid)
            ->select(DB::raw("to_char(add_time, 'yyyy-mm-dd') as add_time"))
            ->where('pay_state',2)
            ->whereBetween('add_time', $where)->get()->toArray();
        return Tools::getGroupCountByAttr($regTrendList, 'add_time');
    }

    /**
     * 获取订单金额
     *
     * @param $sid
     * @param $startDate
     * @param $endDate
     * @return array
     */
    public function getOrderPayAmountByTimeRange($sid,$startDate, $endDate)
    {
        $whereBetween = [$startDate, $endDate];
        $regTrendList = DB::table('vshops_order')
            ->where('sid',$sid)
            ->select(DB::raw("to_char(add_time, 'yyyy-mm-dd') as add_time,make_money"))
            ->whereBetween('add_time', $whereBetween)
            ->where('pay_state',2)
            ->get()->toArray();
        return Tools::getGroupCountByAttr($regTrendList, 'add_time', 'make_money');
    }

}